<?php defined('SYSPATH') OR die('No direct access allowed.');

class Auth_Controller extends Frontend_Controller {

public $history = FALSE;

  public function __construct() {
    parent::__construct();
		$this->template->head['css']['media/css/auth.css'] = 'all';
		$this->template->page = new View('auth/page');
		$this->template->header = new View('layout/header');
		$this->template->footer = new View('layout/footer');
  }

  public function index() {
      $this->user OR url::redirect(url::base().Router::uri('auth', array('method'=>'login')));
			url::redirect($this->get_referrer());
  }

  public function login() {
    if ($this->user) {
			message::add(Kohana::lang('auth.messages.must_logout'), 'warning');
			url::redirect($this->get_referrer());
		}
    if ($post = $this->input->post()) {
      // введены данные формы
			$user = ORM::factory('user', $post['username']);
			if (!$user->loaded) {
				message::add(Kohana::lang('auth.username.exists'), 'error');
				message::add(array('username'=>$post['username']), 'custom');
				url::redirect(Router::$current_uri);
			}
			if (!$user->activated) {
				message::add(Kohana::lang('auth.login.activation_required'), 'error');
				message::add(array('username'=>$post['username']), 'custom');
				url::redirect(Router::$current_uri);
			}
      if ($this->auth->login($post['username'], $post['password'])) {
				Event::run('auth.login');
				message::add(Kohana::lang('auth.login.result_ok', $post['username']), 'success');
				if ($goto = $this->get_referrer()) {
					url::redirect($goto);
				}
				else
					url::redirect();
      }
      else {
				message::add(Kohana::lang('auth.login.result_failed'), 'error');
				message::add(array('username'=>$post['username']), 'custom');
				url::redirect(Router::$current_uri);
			}
    }
		$this->template->head['title'] = Kohana::lang('auth.login.title');
    $this->template->page->content = new View('auth/login');
  }

  public function logout() {
    $this->user OR url::redirect(url::base().Router::uri('auth', array('method'=>'login')));
    if ($this->auth->logout()) {
			Event::run('auth.logout');
			message::add(Kohana::lang('auth.logout.result_ok'), 'success');
      $goto = $this->get_referrer() OR $goto = '';
			url::redirect($goto);
    }
  }

  public function register() {
    if ($this->user) {
			message::add(Kohana::lang('auth.must_logout'), 'warning');
			url::redirect($this->get_referrer());
		}
    //$this->template->title = 'Регистрация нового пользователя';
    $errors = $data = array();
    if ($this->input->post()) {
        // введены данные формы
        $errors = $data = array(
          'email'							=> '',
          'email_confirm'			=> '',
          'username'					=> '',
          'password'					=> '',
          'password_confirm'	=> '',
					'captcha'						=> '',
        );
				$data = arr::overwrite($data, $_POST);
				$this->user = ORM::factory('user');
				$this->user->role = 'user';
				$this->user->created = time();
				if (!$this->user->validate($data)) {
					message::add_validation($data->errors("auth"));
					arr::remove('password', $_POST);
					arr::remove('password_confirm', $_POST);
					message::add($_POST, 'custom');
					url::redirect(Router::uri('auth', array('method'=>'register')));
				}
				else {
					// validation passed
					if (Kohana::config('cms.confirm_registration') === TRUE) {
						$this->activated = FALSE;
						$this->user->confirm_code = $confirm_code = text::random('alnum', 16);
						// send email
						$to = $this->user->email;
						$from = 'biakaveron@gmail.com';
						$subject = Kohana::lang('auth.register.mail_subject');
						$message = Kohana::lang('auth.register.mail_message', array($data['username'], $data['password'], $confirm_code));
						email::send($to, $from, $subject, $message, TRUE);
						message::add(Kohana::lang('auth.register.result_sent'), 'success');
					}
					else {
						$this->user->activated = TRUE;
						message::add(Kohana::lang('auth.register.result_ok'), 'success');
						url::redirect(Router::uri('auth', array('method'=>'login')));
					}
					$this->user->save();
					url::redirect(Router::uri('auth', array('method'=>'login')));
				}
		}
		$this->template->head['title'] = Kohana::lang('auth.register.title');
    $this->template->page->content = new View('auth/register');
  }

	public function activate() {
    if ($this->user) {
			message::add(Kohana::lang('auth.messages.must_logout'), 'warning');
			url::redirect($this->get_referrer());
		}
		if (! $username = $this->input->get('username', FALSE)) {
			// error? goto 404
			Event::run('system.404');
		}
		$user = ORM::factory('user', $username);
		if (!$user->loaded) {
			message::add(array('username'=>$username), 'custom');
			message::add(Kohana::lang('auth.register.wrong_username'), 'error');
			url::redirect(Router::uri('auth', array('method'=>'login')));
		}
		if ($user->activated) {
			// there is no password recoverying!
			message::add(array('username'=>$username), 'custom');
			message::add(Kohana::lang('auth.register.already_activated'), 'info');
			url::redirect(Router::uri('auth', array('method'=>'login')));
		}
		if (strcmp($user->confirm_code, $this->input->get('confirm_code', FALSE)) !== 0) {
			// confirmation code not match
			message::add(array('username'=>$username), 'custom');
			message::add(Kohana::lang('auth.register.wrong_confirmation'), 'error');
			url::redirect(Router::uri('auth', array('method'=>'login')));
		}
		$user->activate();
		message::add(Kohana::lang('auth.register.result_activated'), 'success');
		message::add($username, 'custom');
		Event::run('auth.activated', $user);
		url::redirect(Router::uri('auth', array('method'=>'login')));
	}

	public function pass_recovery() {
    if ($this->user) {
			message::add(Kohana::lang('auth.messages.must_logout'), 'warning');
			url::redirect($this->get_referrer());
		}
		if ($data = $this->input->post()) {
			$user = ORM::factory('user', $data['username']);
			if (!$user->loaded) {
				message::add($data, 'custom');
				message::add_validation(array('username'=>'exists'), 'auth');
				url::redirect(Router::$current_uri);
			}
			if (strcasecmp($user->email, $data['email']) !== 0) {
				message::add($data, 'custom');
				message::add_validation(array('email'=>'match'), 'auth');
				url::redirect(Router::$current_uri);
			}
			// generate new password
			$newpassword = text::random('alnum', 8);
			// and confirmation code
			$confirm_code = text::random('alnum', 16);
			$user->new_password = $newpassword;
			$user->confirm_code = $confirm_code;
			$user->save();
			// send email
			$to = $user->email;
			$from = 'biakaveron@gmail.com';
			$subject = Kohana::lang('auth.recovery.mail_subject');
			$message = Kohana::lang('auth.recovery.mail_message', array($user->username, $newpassword, $confirm_code));
			email::send($to, $from, $subject, $message, TRUE);
			message::add(Kohana::lang('auth.recovery.result_sent', $user->email), 'success');
			//message::add($data, 'custom');
			//url::redirect(Router::uri('auth', array('method'=>'pass_sent')));
			url::redirect(Router::uri('auth', array('method'=>'login')));
		}
		$this->template->head['title'] = Kohana::lang('auth.recovery.title');
		$this->template->page->content = new View('auth/recovery');
	}

	/*public function pass_sent() {
		$this->user AND url::redirect($this->get_referrer());
		if (message::has_custom()) {
			// show page with information about recovery email sent
			$this->template->page->content = new View('auth/recovery_sent');
		}
		else {
			// error? goto 404
			Event::run('system.404');
		}
	}*/

	public function confirm_recovery() {
		if ($this->user) {
			message::add(Kohana::lang('auth.messages.must_logout', 'warning'));
			url::redirect($this->get_referrer());
		}
		if ($username = $this->input->get('username', FALSE)) {
			$user = ORM::factory('user', $username);
			if (!$user->loaded) {
				message::add(array('username'=>$username), 'custom');
				message::add(Kohana::lang('auth.recovery.wrong_username', $username), 'error');
				url::redirect(Router::$current_uri);
			}
			if (is_null($user->confirm_code) OR is_null($user->new_password)) {
				// there is no password recoverying!
				message::add(array('username'=>$username), 'custom');
				message::add(Kohana::lang('auth.recovery.no_data'), 'error');
				url::redirect(Router::$current_uri);
			}
			if (strcmp($user->confirm_code, $this->input->get('confirm_code', FALSE)) !== 0) {
				// confirmation code not match
				message::add(array('username'=>$username), 'custom');
				message::add(Kohana::lang('auth.recovery.wrong_confirmation'), 'error');
				url::redirect(Router::$current_uri);
			}
			$user->recovery_pass();
			message::add(Kohana::lang('auth.recovery.result_ok'), 'success');
			message::add($username, 'custom');
			url::redirect(Router::uri('auth', array('method'=>'login')));
		}
		elseif (message::has_custom()) {
			$this->template->head['title'] = Kohana::lang('auth.recovery.title');
			$this->template->page->content = new View('auth/recovery_result');
		}
		else {
			// error? goto 404
			Event::run('system.404');
		}
	}

 /* public function profile($id = NULL) {
		$this->history = TRUE;
		$user = is_numeric($id) ? ORM::factory('user', intval($id)) : $this->user;
		$user->loaded OR Event::run('system.404');
    $this->template->title = 'Профиль пользователя '.$user->username;
    $this->template->page->content = new View('auth/profile');
    $this->template->page->content->errors = array();
    $userdata = ORM::factory('user_detail', $user->id);
    $this->template->page->content->userdata = arr::merge($user->as_array(), $userdata->as_array());
  }*/

 /* public function change_profile($id = NULL) {
      $this->user OR url::redirect(url::base().Router::uri('auth', array('method'=>'login')));
      $errors = $data = array();
      $userdata = ORM::factory('user_detail', $this->user->id);
      if ($this->input->post()) {
        // введены данные формы
        $data = array(
          'first_name' =>   '',
          'last_name' =>    '',
          'middle_name' =>  '',
          'city' =>         '',
          'interests' =>    '',
          'about' =>        '',
          'website' =>      '',
          'icq' =>          '',
          'jabber' =>       '',
        );
        $data = arr::overwrite($data, $_POST);
        if (!$userdata->validate($data)) {
					message::add_validation($data->errors(), "auth");
					message::add($_POST, 'custom');
        }
        else {
          $userdata->user_id = $this->user->id;
          if ($userdata->save()) {
						message::add(array('result'=>Kohana::lang('auth.profile_ok')), 'success');
					  url::redirect(url::base().Router::uri('auth', array('method'=>'change_profile')));
					}
          else message::add(array('result'=>Kohana::lang('auth.profile_error'), 'error'));
        }
      }
			message::add($userdata->as_array(), 'custom');
      $this->template->page->content = new View('auth/edit_profile');
      $this->template->title = 'Ваша анкета';
    }*/
}
